<?php

namespace App\Http\Middleware;

use Closure;

class PadResponseFormat
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        if($response->getstatusCode()==200) {
            $data = $response->getData();
            if(!$data->data) {
                unset($data->data);
            }
            $response->setData($data);
            return $response;

        }

        if($response->getstatusCode()==422) {
            $data = $response->getData();
            $data->message=current($data->errors)[0];
            $response->setData($data);
            return $response;

        }

        return $next($request);
    }
}
